package com.xq.shop.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author gaoxiaojin
 */
@Component
public class Redis {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired(required = false)
    public Redis(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Value("${spring.redis.default-expire-time}")
    private Long defaultExpireTime;

    public boolean set(final String key, Object value) {
        return set(key, value, defaultExpireTime);
    }

    public boolean set(final String key, Object value, Long expireTime) {
        try {
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value, expireTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    public boolean exists(final String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    public String existsLike(Integer userId) {
        Set<String> strings = redisTemplate.keys("*" + "-" + userId);
        if (Objects.isNull(strings)) {
            return null;
        }
        if (!strings.isEmpty()) {
            for (String s : strings) {
                return s;
            }
        }
        return null;
    }

    public String existsLike(String token, Integer type) {
        Set<String> strings = redisTemplate.keys(token + "*");
        if (Objects.isNull(strings)) {
            return null;
        }
        if (!strings.isEmpty()) {
            for (String s : strings) {
                if (type == 1) {
                    return s;
                } else {
                    // 0只返回有效token
                    if (!s.contains("X")) {
                        return s;
                    }
                }
            }
        }
        return null;
    }

    public Set<String> existsLike2(String key) {
        return redisTemplate.keys("*" + key);
    }

    public Object get(final String key) {
        Object result;
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
}
